StringUtil = {}

StringUtil.split = function(text, delimiter, trim)
	assert(string.len(delimiter) == 1, "Invalid delimiter for split")

	text = string.gsub(text, delimiter .. "+" , delimiter)

	local length, idx, pos = string.len(text), 1, 1
	local result, count = {}, 0

	while idx <= length do
		if string.char(string.byte(text, idx)) == delimiter then
			if idx > pos then
				local part = string.sub(text, pos, idx - 1)
				if trim == true then
					part = StringUtil.trim(part)
				end
				table.insert(result, part)
				count = count + 1
			end
			idx = idx + 1
			pos = idx
		end

		if idx == length then
			local part = string.sub(text, pos, idx)
			if trim == true then
				part = StringUtil.trim(part)
			end
			table.insert(result, part)
			count = count + 1
		end
		idx = idx + 1
	end
	return count, result
end

StringUtil.trim = function(text)
	local trimLeft = string.gsub(text, "^%s+", "")
	return string.gsub(trimLeft, "%s+$", "")
end
